import React from 'react'
import MatchModel from "../../../model/Match";
import Admin from "../../../layout/Admin";
import moment from "moment";
import {Button, DatePicker, Input, Table, Modal, Form, TimePicker,} from "antd";
import {LeftOutlined, RightOutlined,} from '@ant-design/icons';
import Info from "../../../service/info";
import {copyToClip} from "../../../service/copy";

class PushMatch extends React.Component {
    constructor(props) {
        super(props)
        this.model = new MatchModel()
        this.state = {
            p: 0,
            date: moment().format('YYYYMMDD'),
            key: '',
            list: [],
            match: null,
            pushForm: {
                title: '',
                body: '',
                expire: {
                    date: moment(),
                    time: moment(),
                },
            },
            addVodLinkForm: {
                info: [],
                link: '',
                linkTitle: '',
            },
            matchDesc: '',
            modal: {
                push: false,
                addVodLink: false,
                hot: false,
            },
            hot: [],
            hotEvent: '',
        }
    }

    componentDidMount() {
        this.all()
        this.hot()
    }

    all() {
        this.model
            .all({
                p: this.state.p,
                date: this.state.date,
            })
            .then(res => {
                const list = res.data.ok
                this.setState({
                    list,
                })
            })
    }

    hot() {
        this.model
            .hot()
            .then(res => {
                this.setState({
                    hot: res.data.ok.zq,
                })
            })
    }

    search = () => {

        this.model
            .get({
                key: this.state.key, //关键字
                p: this.state.p, //第几页，从0开始，一页返回20条
            })
            .then(res => {
                const list = res.data.ok
                this.setState({
                    list,
                })
            })
    }

    onDeleteInfoItem = (item, index) => {
        const info = [...this.state.addVodLinkForm.info]
        info.splice(index, 1)
        this.setState({
            addVodLinkForm: {
                ...this.state.addVodLinkForm,
                info: info,
            }
        })
    }

    onDeleteZhiboItem = (item, index) => {
        const zhibo = [...this.state.match.zhibo]
        zhibo.splice(index, 1)
        this.setState({
            match: {
                ...this.state.match,
                zhibo: zhibo,
            }
        })
    }

    modalControl = (key, value) => {
        this.setState({
            modal: {
                ...this.state.modal,
                [key]: value,
            }
        })
    }

    callPushMatch = (match) => {

        this.setState({
            match: match,
            matchDesc: `${match.name[0]} - ${match.zhuname[0]} vs ${match.kename[0]}`,
            modal: {
                push: true,
            }
        })

    }

    callAddVodLink = (match) => {
        this.setState({
            match: match,
            matchDesc: `${match.name[0]} - ${match.zhuname[0]} vs ${match.kename[0]}`,

        }, () => {
            this.setState({
                modal: {
                    addVodLink: true,
                }
            })
        })
    }

    addVodLinkInfo = () => {
        const form = this.state.addVodLinkForm
        const info = [...form.info]
        const title = form.linkTitle
        const link = form.link
        if (title && link) {
            info.push([title, link,])
            this.addVodLinkForm.resetFields()
            this.setState({
                addVodLinkForm: {
                    ...this.state.addVodLinkForm,
                    info: info,
                }
            })
        }
    }

    onAddVodLink = () => {
        const namiid = this.state.match.namiid
        const zhibo = this.state.match.zhibo ? this.state.match.zhibo : []
        const info = [...zhibo, ...this.state.addVodLinkForm.info,]

        this.model
            .addVodLink({
                namiid,
                info: JSON.stringify(info),
            })
            .then(res => {
                if (res.data.ok === 1) {
                    Info.success('修改成功')
                    this.setState({
                        addVodLinkForm: {
                            info: [],
                            link: '',
                            linkTitle: '',
                        },
                    }, () => {
                        this.modalControl('addVodLink', false,)
                    })
                }
            })
            .then(() => {
                this.setState({
                    p: 0,
                    date: moment().format('YYYYMMDD'),
                }, () => this.all())
            })
    }

    onPushMatch = (form) => {

        const match = this.state.match
        const ext = JSON.stringify({
            style: 1,
            id: match.namiid,
        })
        const date = this.state.pushForm.expire.date
        const time = this.state.pushForm.expire.time
        const dateStr = date.format('YYYYMMDD')
        const timeStr = time.format('HH:mm:ss')
        const expire = `${dateStr} ${timeStr}`

        this.model
            .push({...form, ext, expire,})
            .then(res => {
                if (res.data.ok === 1) {
                    Info.success('推送成功')
                    this.setState({
                        modal: {push: false,}
                    })
                    this.form.resetFields()
                }
            })

    }

    prevPage() {
        this.setState({
            p: this.state.p - 1,
        }, () => {
            if (this.state.key !== '') {
                this.search()
            } else {
                this.all()
            }
        })
    }

    nextPage() {
        this.setState({
            p: this.state.p + 1,
        }, () => {
            if (this.state.key !== '') {
                this.search()
            } else {
                this.all()
            }
        })
    }

    onDateChange(e) {
        const date = e.format('YYYYMMDD')
        this.setState(({
            p: 0,
            date,
        }), () => this.all())
    }

    copyMatchH5Link = (match) => {
        const id = match.namiid
        const link = `http://www.youtoball.com:8080/game/${id}`
        const result = copyToClip(link)
        result ? Info.success('复制成功') : Info.error('复制出错')
    }

    statusMapper() {
        return {
            0: '比赛异常',
            1: '未开赛',
            2: '上半场',
            3: '中场',
            4: '下半场',
            5: '加时赛',
            7: '点球决战',
            8: '完场',
            9: '推迟',
            10:	'中断',
            11:	'腰斩',
            12:	'取消',
            13:	'待定',
        }
    }

    addHotEvent = () => {
        const event = this.state.hotEvent
        const hot = this.state.hot
        hot.push(event)
        this.setState({
            hot: [...hot,],
            hotEvent: '',
        })
    }

    deleteHotEvent = (index) => {
        const hot = this.state.hot
        hot.splice(index, 1)
        this.setState({
            hot: [...hot,],
        })
    }

    submitHot = () => {
        const hot = this.state.hot
        this.model.setHot({
            Games: hot,
        }).then(res => {
            if (res.data.ok) {
                Info.success('编辑成功')
            }
        }).then(() => {
            this.setState({
                hotEvent: '',
                modal: {
                    ...this.state.modal,
                    hot: false,
                }
            })
        }).then(() => this.hot())
    }

    render() {
        const columns = [
        // daxiao: null
        // detail: ""
        // donghua: 0
        // dxresult: 0
        // id: 24
        // jieduangroup: 0
        // jieduanid: 46556
        // jieduanlun: 0
        // jieduanmode: 2
        // jieduanname: ["六月", "六月", "June"]
        // jieduanround: 0
        // jieduanzu: 0
        // keaddfen: 0
        // kedianfen: 0
        // kefen: 1
        // kehalffen: 1
        // kehong: 0
        // kehuang: 0
        // keid: 15203
        // kejiao: 0
        // kelogo: "ce37d84133489e22d48ef180d40b76c2.png"
        // kename: ["北京人和", "北京人和", "Beijing Renhe"]
        // kerank: ""
        // logo: "2440249cd19586c39de8e05d55cc6b0d.png"
        // lunci: 0
        // name: ["球会友谊", "球會友誼", "INT CF"]
        // namiid: 3393457
        // qingbao: 0
        // rangqiu: null
        // rqresult: 0
        // saijiid: 9402
        // saijiyear: "2020"
        // shengps: null
        // spsresult: 0
        // startballt: 1592294400
        // startt: 1592292600
        // state: 8
        // zhenrong: 0
        // zhongli: 0
        // zhuaddfen: 0
        // zhudianfen: 0
        // zhufen: 3
        // zhuhalffen: 1
        // zhuhong: 0
        // zhuhuang: 0
        // zhuid: 48389
        // zhujiao: 0
        // zhulogo: "db59f5aa5e705a3c29c324749bc303e3.png"
        // zhuname: ["泰州远大", "泰州遠大", "Taizhou Yuanda"]
        // zhurank: ""
            {
                title: '纳米ID',
                dataIndex: 'namiid',
                render: (text,) => text,
            },
            {
                title: '联赛',
                dataIndex: 'name',
                render: (text,) => text[0],
            },
            {
                title: '主队',
                dataIndex: 'zhuname',
                render: (text,) => text[0],
            },
            {
                title: '客队',
                dataIndex: 'kename',
                render: (text,) => text[0],
            },
            {
                title: '比分',
                render: (text,) => `${text.zhufen} vs ${text.kefen}`,
            },
            {
                title: '状态',
                dataIndex: 'state',
                render: (text) => this.statusMapper()[Number(text)],
            },
            {
                title: '开赛时间',
                dataIndex: 'startt',
                render: (text) => moment(new Date(text * 1000)).format('YYYY-MM-DD HH:mm'),
            },

            {
                title: '开球时间',
                dataIndex: 'startballt',
                render: (text) => moment(new Date(text * 1000)).format('YYYY-MM-DD HH:mm'),
            },


            {
                title: '让球',
                dataIndex: 'rangqiu',
                render: (text) => text && text.join(','),
            },

            {
                title: '大小球',
                dataIndex: 'daxiao',
                render: (text) => text && text.join(','),
            },

            {
                title: '胜平负',
                dataIndex: 'shengps',
                render: (text) => text && text.join(','),
            },

            {
                title: '操作',
                render: (record) => (
                    <div>
                        <a
                            onClick={() => this.callPushMatch(record)}
                            style={{marginRight: '8px',}}
                        >推送</a>

                        <a
                            onClick={() => this.callAddVodLink(record)}
                            style={{marginRight: '8px',}}

                        >添加视频</a>
                        <a
                            onClick={() => this.copyMatchH5Link(record)}
                        >
                            复制H5链接
                        </a>
                    </div>
                )
            }
        ]
        const footer = <div style={{
            paddingTop: 8,
            display: "flex",
            justifyContent: "flex-end",
        }}>
            <Button
                style={{marginRight: 8,}}
                onClick={(e) => this.prevPage()}
            ><LeftOutlined /></Button>
            <a className='ant-pagination-item ant-pagination-item-active '>{this.state.p + 1}</a>
            <Button
                onClick={(e) => this.nextPage()}
            ><RightOutlined /></Button>
        </div>

        const table = <div className='list-container'>
            <div style={{marginBottom: '8px',}}>
                <Button
                    style={{marginRight: '8px',}}
                    onClick={() => this.modalControl('hot', true)}
                >
                    编辑重要赛事
                </Button>
                <DatePicker
                    defaultValue={moment()}
                    defaultPickerValue={moment()}
                    onChange={e => this.onDateChange(e)}
                />
                <Input
                    placeholder='关键字'
                    style={{width: '200px', marginLeft: '8px', marginRight: '8px',}}
                    value={this.state.key}
                    onChange={e => this.setState({key: e.target.value})}
                />
                <Button onClick={() => {
                    this.setState({p: 0}, () => this.search())
                }}>搜索</Button>
            </div>

            <Table
                rowKey={(record, index) => index}
                dataSource={this.state.list}
                columns={columns}
                // rowKey={(record, index) => index}
                pagination={false}
            />
            {footer}
        </div>

        const layout = {
            labelCol: { span: 6 },
            wrapperCol: { span: 16 },
        }


        const pushModal = <Modal
            title={'推送比赛: ' + this.state.matchDesc}
            visible={this.state.modal.push}
            footer={null}
            maskClosable={true}
            onCancel={() => this.setState({
                modal: {
                    push: false,
                },
                matchDesc: '',
                match: null,
            })}
        >

            <Form
                {...layout}
                ref={el => this.form = el}
                initialValues={this.state.pushForm}
                onFinish={this.onPushMatch}
            >
                <Form.Item
                    label="标题"
                    name="title"
                >
                    <Input />
                </Form.Item>
                <Form.Item
                    label="内容"
                    name="body"
                >
                    <Input.TextArea />
                </Form.Item>

                <Form.Item label="推送日期">
                    <DatePicker
                        value={this.state.pushForm.expire.date}
                        onChange={value => this.setState({
                            pushForm: {
                                expire: {
                                    ...this.state.pushForm.expire,
                                    // 20060102 13:04:05
                                    date: value,
                                }
                            }
                        })}
                    />
                    <TimePicker
                        value={this.state.pushForm.expire.time}
                        onChange={value => this.setState({
                            pushForm: {
                                expire: {
                                    ...this.state.pushForm.expire,
                                    // 20060102 13:04:05
                                    time: value,
                                }
                            }
                        })}
                    />
                </Form.Item>

                <Form.Item wrapperCol={{ ...layout.wrapperCol, offset: 6 }}>

                    <Button onClick={() => this.setState({modal: {push: false,}})}  style={{marginRight: '8px',}}>
                        取消
                    </Button>

                    <Button type="primary" htmlType="submit">
                        推送
                    </Button>

                </Form.Item>

            </Form>

        </Modal>

        const match = this.state.match
        let linkArr = []
        if (match) {
            linkArr = match.zhibo ? match.zhibo : []
        }

        let info = this.state.addVodLinkForm.info

        const addVodLinkModal = <Modal
            width={1000}
            title={'添加视频源： ' + this.state.matchDesc}
            visible={this.state.modal.addVodLink}
            footer={null}
            maskClosable={true}
            onCancel={() => this.setState({
                modal: {
                    addVodLink: false,
                },
                matchDesc: '',
                match: null,
            })}
        >
            <Form
                {...layout}
                ref={el => this.addVodLinkForm = el}
                // initialValues={this.state.addVodLinkForm}
                onFinish={this.onAddVodLink}
            >
                <Form.Item
                    label="视频源名城"
                    name="linkTitle"
                >
                    <Input
                        onChange={e => this.setState({
                            addVodLinkForm: {
                                ...this.state.addVodLinkForm,
                                linkTitle: e.target.value,
                            }
                        })}
                        value={this.state.addVodLinkForm.linkTitle}
                    />
                </Form.Item>
                <Form.Item
                    label="视频源"
                    name="link"
                >
                    <Input
                        value={this.state.addVodLinkForm.linkTitle}
                        onChange={e => this.setState({
                            addVodLinkForm: {
                                ...this.state.addVodLinkForm,
                                link: e.target.value,
                            }})
                        }
                    />
                </Form.Item>

                <Form.Item
                    label="操作"
                >
                    <Button
                        type="primary"
                        onClick={this.addVodLinkInfo}
                    >
                        添加
                    </Button>
                </Form.Item>

                <Form.Item
                    label="现有直播信号"
                >
                    {linkArr.length === 0
                        ? '暂无'
                        : linkArr.map((link, index) => {
                            let [title, value] = link
                            return <div key={title}>
                                <div>{title}: {value}</div>
                                <div>
                                    <Button
                                        onClick={(e) => this.onDeleteZhiboItem(link, index)}
                                    >删除</Button>
                                </div>
                            </div>
                        })
                    }
                </Form.Item>

                <Form.Item
                    label="新增直播信号"
                >
                    {info.length === 0
                        ? '暂无'
                        : info.map((link, index) => {
                            let [title, value] = link
                            return <div key={title}>
                                <div>{title}: {value}</div>
                                <div>
                                    <Button
                                        onClick={(e) => this.onDeleteInfoItem(link, index)}
                                    >删除</Button>
                                </div>
                            </div>
                        })
                    }
                </Form.Item>

                <Form.Item wrapperCol={{ ...layout.wrapperCol, offset: 6 }}>

                    <Button onClick={() => this.setState({modal: {addVodLink: false,}})}  style={{marginRight: '8px',}}>
                        取消
                    </Button>


                    <Button type="primary" htmlType="submit">
                        确定修改
                    </Button>

                </Form.Item>
            </Form>
        </Modal>
        const hotModal = <Modal
            visible={this.state.modal.hot}
            onCancel={() => this.modalControl('hot', false)}
            title='足球重要赛事'
            onOk={() => this.submitHot()}
        >
            {this.state.hot.map((event, index) => {
                return <div style={{width: '100%', marginBottom: '8px', display: 'flex', justifyContent: 'space-between',}} key={index}>
                    <span>{event}</span>
                    <Button
                        onClick={() => this.deleteHotEvent(index)}
                    >
                        删除
                    </Button>
                </div>
            })}
            <div style={{display: 'flex',}}>
                <Input
                    value={this.state.hotEvent}
                    onChange={e => this.setState({hotEvent: e.target.value,})}
                    placeholder='输入重要赛事名称'
                />
                <Button
                    onClick={this.addHotEvent}
                >
                    添加
                </Button>
            </div>

        </Modal>
        return <>
            {pushModal}
            {addVodLinkModal}
            {hotModal}
            <Admin>
                {table}
            </Admin>
        </>
    }

}



export default PushMatch


